import os
import time
import platform
import sys
import matplotlib.pyplot as plt
import cv2


def listdir(path):  # 传入存储的list
    datanames = os.listdir(path)
    file_list = []
    for dataname in datanames:
        if os.path.splitext(dataname)[-1] == '.mp4' or os.path.splitext(dataname)[-1] == '.avi':  # 目录下包含.json的文件
            file_list.append(dataname)
    return file_list


def getfilename(filename):
    for root, dirs, files in os.walk(filename):
        array = dirs
        if array:
            print(array)
            return array


def analysis(in_path):
    video_list = listdir(in_path)
    save_path = in_path + '/Analysis_Result'

    if not os.path.exists(save_path):
        os.mkdir(save_path)

    # 写入max数据到本地表格
    file1 = open(save_path + '/' + 'result' + '.csv', 'a')
    file1.writelines(
        "video_Name" + ',' + "video_Resolution" + ',' + "Average_Rate" + ',' + "Lost_Frame" + "," + 'Max_Val' + "," + "Video_Duration(s)" + "," + 'analysisTime(s)' + "\n")
    video_type = []
    resolution_list = []
    average_frame_list = []
    Video_duration_list = []
    lost_frame_list = []
    Max_Val = []
    Analysis_Time = []
    for video_name in video_list:
        time_start = time.time()
        # handle_cur_video.setText(video_name)

        full_path = in_path + '/' + video_name
        # print(full_path)

        cap = cv2.VideoCapture(full_path)

        frame_count = 0
        success = True

        frame_num = cap.get(7)  # frame number get方法参数按顺序对应下表（从0开始编号，比如这里为了获取视频的总帧数，在下表是排第八个的
        frame_rate = round(cap.get(5), 3)  # frame rate

        height = int(cap.get(4))  # frame height
        width = int(cap.get(3))  # frame width
        print(height, width)

        interval = []
        pre = 0
        x = []

        # cap.isOpened()

        print("----------waiting to analysis-----------")
        while (success):
            # for i in range(20):
            success, frame = cap.read()
            milliseconds = cap.get(cv2.CAP_PROP_POS_MSEC)
            cur = milliseconds
            cur_interval = (cur - pre) / 1000
            # cur_interval=("%.7f" % cur_interval)
            interval.append(float(cur_interval))
            pre = milliseconds
            # print ('Read a new frame: ', success)
            # print (milliseconds)

            frame_count += 1
            x.append(frame_count)
            print(x)
            print(interval)
        print('Analyzing ' + str(frame_count) + ' Frame.')

        cap.release()
        # cv2.destroyAllWindows()#关闭窗口

        # print(interval[0:-1])
        # print(x[0:-1])

        time_end = time.time()
        time_period = round(time_end - time_start, 2)
        print('total time:', time_period)
        print(frame_count)

        # print(type(interval[0]))

        data_x = x
        data_y = interval
        peak_val = round(max(data_y), 5)
        #  解决图片以中文名的问题
        plt.rcParams['font.sans-serif'] = ['SimHei']  # 黑体
        plt.figure()
        plt.plot(data_x, data_y, 'b')
        plt.title(video_name + '   The biggest interval is:' + str(peak_val) + 's')
        plt.savefig(save_path + '/' + video_name[:-4] + ".png")

        lost_frame = (float(peak_val) / (float((1 / frame_rate)))) - 1
        video_times = round(frame_count / frame_rate, 2)
        # 写入max、视频分辨率、视频平均帧率数据到本地表格
        file1.writelines(video_name[:-4] + ',' + str(str(width) + str("x") + str(height)) + "," + str(frame_rate)
                         + ',' + str(round(lost_frame, 2)) + "," + str(peak_val) + ',' + str(video_times) + "," + str(
            time_period) + "\n")
        video_type.append(str(video_name[:-4]))
        resolution_list.append((str(width) + str("x") + str(height)))
        average_frame_list.append(str(frame_rate))
        Video_duration_list.append(str(video_times))
        lost_frame_list.append(str(round(lost_frame)))
        Max_Val.append(str(peak_val))
        Analysis_Time.append(str(time_period))
    data_list = [video_type, resolution_list, average_frame_list, Video_duration_list, lost_frame_list, Max_Val,
                 Analysis_Time]
    revert = [[row[i] for row in data_list] for i in range(len(data_list[0]))]
    print(revert)
    file1.close()
    return revert


# 获取当前目录
def get_category():
    print("当前路径为：%s" % os.path.abspath("."))
    return os.path.abspath(".")


def pull_to_local(local_path):
    camera_path = "/sdcard/DCIM/Camera/"
    pull_cmd = "adb -s %s pull %s %s" % (devices, camera_path, local_path)
    del_cmd = "adb -s %s shell rm -rf %s" % (devices, camera_path)
    print("把已录制 %s 视频pull到本地path %s" % (camera_path, local_path))
    return run_cmd(pull_cmd)


def del_cmd():
    camera_path = "/sdcard/DCIM/Camera/"
    del_cmd = "adb -s %s shell rm -rf %s" % (devices, camera_path)
    print("删除手机内文件")
    return run_cmd(del_cmd)


def run_cmd(cmd):
    return os.system(cmd)


# devices = sys.argv[1]
devices = "92310ak1"
video_path = get_category()
getfilename(video_path)
pull_to_local(video_path)
del_cmd()
analysis(r"D:\PyCharmProject\pythonDemo2\Result\2021-11-04\2" + "\Camera")

if __name__ == '__main__':
    print(video_path)
